package main

import (
	"database/sql"
	"errors"
	"github.com/gin-gonic/gin"
	_ "github.com/mattn/go-sqlite3"
	log "github.com/sirupsen/logrus"
	"net"
	"net/http"
	"os"
	"shunfeng_interface"
	"strconv"
)

const Port = 9000

func main() {
	LogInit()
	//获取IP
	ip, err := GetLocalIp()
	if err != err {
		log.Panic(err)
	}

	// 创建一个新的SQLite数据库文件
	db, err := sql.Open("sqlite3", "./shunfeng.db")
	if err != nil {
		log.Panic("sql.Open err:", err)
	}
	defer db.Close()

	//初始化服务
	serve := shunfeng_interface.NewServe(ip, Port, db, 30)
	//启动gin服务
	gin.SetMode(gin.ReleaseMode)
	g := gin.Default()
	g.StaticFS("/images_folder", http.Dir("./images"))
	g.Static("/images", "./images") //图片
	g.Static("/videos", "./videos") //视频
	g.POST("/api/v1/start", serve.Start)
	g.POST("api/v1/stop", serve.Stop)

	log.WithFields(log.Fields{"ip": ip, "port": Port}).Info("shunfeng interface serve start success")
	g.Run(":" + strconv.Itoa(Port))
}

func LogInit() {
	customFormatter := new(log.TextFormatter)
	customFormatter.TimestampFormat = "2006-01-02 15:04:05.000"
	customFormatter.FullTimestamp = true
	customFormatter.ForceColors = true
	log.SetFormatter(customFormatter)

	//设置log等级
	logLevel, err := log.ParseLevel(os.Getenv("LOG_LEVEL"))
	if err != nil {
		logLevel = log.DebugLevel
	}
	log.SetLevel(logLevel)
}

// GetLocalIp 获取IP
func GetLocalIp() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String(), nil
			}
		}
	}
	return "", errors.New("can not find the client ip address")
}
